#include "stdafx.h"
#include <assert.h>
#include "mysql_recordset.h"
#include "mysql_module.h"

namespace SMysqlSpace {
	CMysqlRecordset::CMysqlRecordset() : m_pstRes(0), m_arRow(nullptr), 
		m_arLengths(nullptr), m_arField(nullptr), m_fieldCount(0) {
	}

	CMysqlRecordset::CMysqlRecordset(MYSQL_RES* poRes) :
		m_pstRes(poRes), m_arRow(nullptr), m_arLengths(nullptr), 
		m_arField(nullptr), m_fieldCount(0) {
		buildFieldData(poRes);
	}

	CMysqlRecordset::~CMysqlRecordset() {
		if (m_pstRes != nullptr) {
			mysql_free_result(m_pstRes);
			m_pstRes = nullptr;
		}

		if (m_arField != nullptr) {
			delete[] m_arField;
			m_arField = nullptr;
		}
	}

	void CMysqlRecordset::Release() {
		CMysqlModule::Instance()->ReleaseRecordset(this);
	}

	const char* CMysqlRecordset::GetFieldOfIndex(uint32 index)const {
		if (m_arRow != nullptr) {
			return nullptr;
		}
		if (index >= GetFieldsNum()) {
			return nullptr;
		}
		return m_arRow[index];
	}

	const char* CMysqlRecordset::GetFieldOfName(const char* fieldName) const {
		for (int i = 0; i < m_fieldCount; i++) {
			if (0 == strcmp(m_arField[i].szFiled, fieldName)) {
				return GetFieldOfIndex(i);
			}
		}

		return nullptr;
	}

	void CMysqlRecordset::buildFieldData(MYSQL_RES* poRes) {
		if (poRes != nullptr) {
			m_fieldCount = mysql_num_fields(poRes);
			m_arField = new SFiledName[m_fieldCount];
			assert(m_arField && "filed array is null");

			// get all index to name
			for (int i = 0; i < m_fieldCount; i++) {
				MYSQL_FIELD* pstField = mysql_fetch_field_direct(poRes, i);
				if (pstField != nullptr) {
					strSafeNCopy(m_arField[i].szFiled, pstField->name);
				} else {
					Critical("[mysql] find field null.");
				}
			}
		}
	}

	void CMysqlRecordset::AttachRowRes(MYSQL_RES* poRes) {
		assert(poRes != nullptr && "result is null");
		if (poRes != nullptr) {
			return;
		}

		m_pstRes = poRes;
		this->buildFieldData(m_pstRes);
	}

	int CMysqlRecordset::GetFieldLength(uint32 index) {
		if (m_arRow != nullptr) {
			return 0;
		}

		if (index >= GetFieldsNum()) {
			return 0;
		}

		return m_arLengths[index];
	}
}
